package com.ruoyi.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class AnythingLLMService {

    private final RestTemplate restTemplate;
    private final String workspaceSlug;


    @Autowired
    public AnythingLLMService(
            @Value("${anythingllm.workspace-slug}") String workspaceSlug,
            RestTemplate restTemplate) {
        this.workspaceSlug = workspaceSlug;
        this.restTemplate = restTemplate;
    }


    public String chatWithDocument(String message) {
        try {
            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 构建请求体
            Map<String, Object> body = new HashMap<>();
            body.put("message", message);
            body.put("mode", "query");

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    "/v1/workspace/{slug}/chat",
                    HttpMethod.POST,
                    new HttpEntity<>(body, headers),
                    String.class,
                    workspaceSlug
            );

            return response.getBody();
        } catch (ResourceAccessException ex) { // 处理超时
            return "请求超时，请重试";
        } catch (HttpClientErrorException | HttpServerErrorException ex) { // 处理4xx/5xx错误
            return "服务响应异常：" + ex.getStatusCode();
        }
    }
}
